<!--海外出库-交接发运-->
<template>
  <div class="page-container" v-loading="loading">
    <div class="search mg_t2">

      <el-form :label-width="$globalCss.formLabelWidth_default" label-position="right" ref="formSearch" :rules="rules"
        :model="{}" onsubmit="return false">

        <el-form-item :label="$tt('label_track_or_collect_code')" prop="searchCode">
          <div class="flex_row_center">
            <scan_input v-model.trim="searchCode" @enterInput="scanPackageNo" style="width:400px"
              class="form_input_default mg_l1" autofocus>
            </scan_input>
            <el-button class="mg_l2" type="primary" @click="scanPackageNo">{{ $tt('label_scan') }}</el-button>
          </div>
        </el-form-item>

      </el-form>
    </div>

    <div class="flex_row flex_justify_sb mg_v2">
      <div class="flex_row">
        <el-button @click="syncConfigClick">{{ $t('label_sync_face_order_config') }}</el-button>
        <el-button @click="manualSyncConfigClick">{{ $t('label_manual_sync_face_order') }}</el-button>

      </div>
      <div class="flex_row">
        <el-button @click="batchSignOut" type="primary">{{ $t('label_handover_shipping') }}</el-button>
        <el-button @click="goToRecord">{{ $t('label_handover_shipping_record') }}</el-button>
      </div>
    </div>


    <ex_super_table ref="MainTable" class="main-table" v-bind="tableOption" :data="tableData" :autoFlex="true"
      :autoPage="false" @selection-change="list => selection = list" @select="selectClick" @row-click="rowClick">
    </ex_super_table>

    <ex_super_dialog_form ref="dialogSyncConfig" v-bind="dialogSyncConfig"
      @afterSubmitSuccess="dialogSyncConfigSubmitSuccess">
    </ex_super_dialog_form>
  </div>
</template>
<script>
// import superTablePageFunction from '@/mixin/super-table-page-function';

export default {
  title: "label_handover_shipping",
  mixins: [],
  components: {},
  data() {
    return {
      loading: false,
      selection: [],
      searchCode: "",
      rules: {
        searchCode: {
          required: true, trigger: 'blur',
          validator: (r, v, cb) => {
            if (_.isEmpty(this.searchCode)) {
              return cb(this.$tt('tip_can_no_empty'))
            }
            cb()
          }
        },
      },



      tableData: [],
      tableOption: {
        attrs: { 'span-method': this.objectSpanMethod, },

        model: [
          {
            type: 'selection',
          },
          { key: 'boxNo', label: 'label_package_collection_no', 'min-width': 120, },

          { key: 'outOrderNo', label: 'label_outbound_code', 'min-width': 140, },
          {
            key: 'customerName', label: 'label_customer_name', 'width': 140, 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode)
          },
          { key: 'packageNo', label: 'label_track_or_package_code', 'min-width': 120, },
          { key: 'supplierName', label: 'label_logistics_supplier', 'min-width': 100, 'show-overflow-tooltip': true, },
          { key: 'transTrackNo', label: 'label_track_code', 'min-width': 100, },
          { key: 'weight', label: 'label_weight', 'width': 100, },
          { key: 'volume', label: 'label_volume', 'width': 100, },
          { key: 'orderNo', label: 'label_order_code', 'min-width': 120, },
          { key: 'skuCount', label: 'label_sku_count', 'width': 100, },
          {
            type: 'operate', 'width': 160, operate: [
              {
                label: "label_remove", type: 'confirm-button', buttonClass: "button_text_danger", confirmButtonType: 'danger',
                message: 'text_confirm_sure_delete',
                done: [(row, i, data, res) => {
                  this.deleteRow(row)
                }]
              },
            ]
          },
        ],

      },
      dialogSyncConfig: {
        customClass: 'dialog_auto',


        submitDataHandle: (data) => {
          data.customerIds = data.customerIds ? data.customerIds.join(',') : ""
          data.supplierIds = data.supplierIds ? data.supplierIds.join(',') : ""
          return data;
        },
        detailDataHandle: (data) => {
          data = data || {}
          data.customerIds = data.customerIds ? data.customerIds.split(',') : []
          data.supplierIds = data.supplierIds ? data.supplierIds.split(',') : []
          return data;
        },
        form: {
          default: { autoSyncFlag: "N" },
          itemClass: "form_item_default", inputClass: "form_input_default",
          model: [
            { label: "label_customer", key: "customerIds", type: 'common_customer_choose', attrs: { multiple: true, }, },

            {
              label: "label_carrier",
              key: "supplierIds",
              type: 'select', attrs: { multiple: true, filterable: true, remote: true, remoteQuery: "keyword", 'reserve-keyword': true, },
              url: '/wms-api/outbound/OutboundBoxPackageRpc/selectSupplierList.json',
              option: (e) => ({ label: this.$formatNameCode(e['supplierName'], e['supplierCode']), value: e['id'] })
            },
            { key: 'autoSyncFlag', label: 'label_auto_sync', type: 'ex_radio_group_auto', enum: 'YesOrNoEnum', if: (data) => !data.manual },
            {
              key: 'tip',
              renderItem: (h, { row }) => {
                return (<el-alert
                  title={this.$t('tip_no_select_will_sync_all_can_face_order')} closable={false}
                  type="warning">
                </el-alert>)
              }
            },
          ],
          rules: {
            'autoSyncFlag': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
          },
        }
      },
    };
  },
  mounted() {

    this.syncConfigGet()

  },

  methods: {
    syncConfigGet() {
      this.loading = true
      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxPackageRpc/querySyncOutPackageList.json",
        method: 'post',
        data: { limit: 1001 },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            res.data.rows.forEach(it => {
              const group = _.groupBy(res.data.rows, t => t.boxNo)
              _.forOwn(group, (v, k) => {
                if (k) {
                  const list = res.data.rows.filter(it => it.boxNo == k)
                  list.forEach((row, i) => {
                    it.collectSpan = i == 0 ? list.length : 0
                    it.link = list
                  })
                }
              })
              // if (!this.tableData.some(o => o.id == it.id)) {
              //   this.tableData.push(it)
              //   console.log(this.tableData)
              // }
            })
            this.tableData = res.data.rows

          }
        },
        failure: () => {
        },
        complete: () => {
          this.loading = false

        }
      })
    },
    manualSyncConfigGet(data) {
      this.loading = true

      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxPackageRpc/syncOutPackageList.json",
        method: 'post',
        data: Object.assign({ limit: 1001 }, data),
        success: (res) => {
          if (res && res.data && res.data.rows) {
            res.data.rows.forEach(it => {
              const group = _.groupBy(res.data.rows, t => t.boxNo)
              _.forOwn(group, (v, k) => {
                if (k) {
                  const list = res.data.rows.filter(it => it.boxNo == k)
                  list.forEach((row, i) => {
                    it.collectSpan = i == 0 ? list.length : 0
                    it.link = list
                  })
                }
              })
            })
            this.tableData = res.data.rows

          }
        },
        failure: () => {
        },
        complete: () => {
          this.loading = false

        }
      })
    },
    syncConfigClick() {
      this.$refs['dialogSyncConfig'].showNew({
        title: this.$t('label_sync_face_order_config'),
        submitUrl: '/wms-api/outbound/OutboundHandoverConfigRpc/saveUpdate.json',
        detailUrl: '/wms-api/outbound/OutboundHandoverConfigRpc/getCurrentConfig.json',
      })
    },
    manualSyncConfigClick() {
      this.$refs['dialogSyncConfig'].showNew({
        title: this.$t('label_manual_sync_face_order'),
        data: {
          manual: true,
        },
        onlySetData: true,
      })
    },
    dialogSyncConfigSubmitSuccess(data) {

      if (data.manual) {
        this.manualSyncConfigGet(data)
      }
    },
    selectClick(selection, row) {
      const check = selection.includes(row)
      this.$nextTick(() => {
        if (row.link) {
          row.link.forEach(it => {
            this.$refs.MainTable.toggleRowSelection(it, check)
          })
        } else {
          this.$refs.MainTable.toggleRowSelection(row, check)

        }

      })
    },
    rowClick(row, column, event) {
      const check = this.selection.includes(row)
      if (row.link) {
        row.link.forEach(it => {
          this.$refs.MainTable.toggleRowSelection(it, !check)
        })
      } else {
        this.$refs.MainTable.toggleRowSelection(row, !check)
      }

    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['boxNo',].includes(column.property)) {
        return { rowspan: row.collectSpan ? row.collectSpan : 1, colspan: 1 }
      }
      if (['selection', 'operate'].includes(column.type)) {
        return { rowspan: row.collectSpan ? row.collectSpan : 1, colspan: 1 }
      }

    },

    deleteRow(row) {
      if (row.link) {
        row.link.forEach(it => {
          const i = this.tableData.indexOf(it)
          if (i >= 0) this.tableData.splice(i, 1)
        })
      } else {
        const i = this.tableData.indexOf(row)
        if (i >= 0) this.tableData.splice(i, 1)
      }

    },
    scanPackageNo() {
      this.$refs.formSearch.validate((valid) => {
        if (valid) {
          if (this.tableData.some(it => it.packageNo == this.searchCode || it.boxNo == this.searchCode)) {
            return this.$message.error(this.$tt('tip_code_has_add', { code: this.searchCode }))
          }
          this.getPackageNoInfo()
        } else {
          return false;
        }
      });

    },
    getPackageNoInfo() {
      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxPackageRpc/matchSignOutPackage.json",
        method: 'post',
        data: {
          packageNo: this.searchCode
        },
        success: (res) => {
          if (res && res.data) {

            if (res.data.rows instanceof Array) {
              let item = _.head(res.data.rows)
              if (this.tableData.some(it => it.supplierId != item.supplierId)) {
                return this.$message.error(this.$tt("tip_noCreate_outboundTotalOrder_noSomeProjuct"))
              }
              res.data.rows.forEach((it, i) => {
                it.collectSpan = i == 0 ? res.data.rows.length : 0
                it.link = res.data.rows
              })
              this.tableData.push(...res.data.rows)
            } else {
              let item = res.data
              if (this.tableData.some(it => it.supplierId != item.supplierId)) {
                return this.$message.error(this.$tt("tip_noCreate_outboundTotalOrder_noSomeProjuct"))
              }
              this.tableData.push(res.data)
            }

          }
        },
        failure: () => {
        },
        complete: () => {
        }
      })
    },
    batchSignOut() {
      let _list = this.selection;
      if (_list.length <= 0) return this.$message.error(this.$tt('tip_please_select_track'))
      let unionCollect = _.unionBy(_list, "boxNo").map(it => it.boxNo).filter(it => it)
      let unionPackageNo = _.unionBy(_list, "packageNo").map(it => it.packageNo).filter(it => it)
      let _readylist = this.tableData.filter(it => unionCollect.includes(it.boxNo) || unionPackageNo.includes(it.packageNo))

      this.$confirm(this.$tt('tip_count_is_confirm_handover_select_track', { count: _readylist.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.submitQueue(_.chunk(_readylist, 50), 0)
      }).catch(() => {
      });

    },
    submitQueue(chunklist, i, loading) {

      if (!loading) {
        loading = this.$loading({
          lock: true,
          text: this.$t('tip_submiting'),
        });
      }
      const willSubmitList = chunklist[i]
      this.submitData(
        {
          list: willSubmitList,
          success: () => {
            willSubmitList.forEach(it => {
              this.deleteRow(it)
            })
            i = i + 1
            if (i == chunklist.length) {
              this.$emitPage('outbound>handover_shipping_record', 'reload')
              this.$emitPage('outbound>handover_file_manage_service', "reload")
              this.$message.success(this.$tt('tip_submit_success'))
              if (_.isEmpty(this.tableData)) {
                this.syncConfigGet()
              }
              if (loading) {
                loading.close()
              }
            } else {
              this.submitQueue(chunklist, i, loading)
            }
          },
          failure: () => {
            if (loading) {
              loading.close()
            }
          }
        })
    },

    submitData({ list, success, failure }) {
      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxPackageRpc/signOut.json",
        method: 'post', type: 'json',
        data: {
          wmsHandoverPackageVoList: list.map(it => {
            let { link, ...other } = it
            return other
          })
        },
        success: (res) => {
          success(list)
          // this.$emitPage('outbound>handover_shipping_record', 'reload')

          // this.$message.success(this.$tt('tip_submit_success'))
          // // this.tableData = []
          // list.forEach(it => {
          //   this.deleteRow(it)
          // })
        },
        failure,
        // complete,
      })
    },
    goToRecord() {
      this.$router.push({ path: "/page/wms/overseas/outbound/handover_shipping_record", query: {} });
    },
  }

};

</script>
<style></style>
